const user = require('user');
const net = require('net');

var conf = null; 
function init(config) {
  conf = config || {};
  net.init(conf);
  user.init(conf);
}

function request(uri, param, callback) {
  // try request remote
  net.send(uri, param, function(err, data){
    if (err) {
      if (err.code == 401) {
        // need login
        user.login(function(err){
          if (err) {
            // login fail
            if (callback) {
              callback(err, null);
            }
          }
          else {
            // login success, post again
            net.send(uri, param, callback);
          }
        });
        return;
      }
    }

    if (callback) {
      callback(err, data);
    }
  });
}

function upload(file, callback) {
	// check user login status first
	user.get(function (err) {
		if (err) {
			if (callback) {
				callback(err, null);
			}
		}
		else {
			// user logined, start upload
			net.upload('/file/upload', file, callback);
		}
	});
}

module.exports = {
  init, request, upload
};